package io.gitee.hefren.hhsharding.utils;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import groovy.lang.Closure;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

import java.util.Map;
import java.util.Objects;

/**
 * @Date 2024/8/21
 * @Author lifei
 */
public class InlineExpressionParser {

    private final String inlineExpression;
    private static final GroovyShell SHELL = new GroovyShell();
    private static final Map<String, Script> SCRIPTS = Maps.newHashMap();


    public InlineExpressionParser(String inlineExpression) {
        this.inlineExpression = inlineExpression;
    }

    public static String handleClosureExpression(String expression) {
        if (Objects.isNull(expression)) {
            return null;
        }
        if (expression.contains("$->{")) {
            return expression.replaceAll("\\$->\\{", "\\$\\{");
        }
        return expression;
    }

    public Closure<?> evaluateInlineExpression() {
        String closureExpression = Strings.lenientFormat("{->\"%s\"}", inlineExpression);
        return (Closure<?>) evaluate(closureExpression);
    }

    public Object evaluate(String expression) {
        Script script;
        if (SCRIPTS.containsKey(expression)) {
            script = SCRIPTS.get(expression);
        } else {
            script = SHELL.parse(expression);
        }
        return script.run();
    }

    public String getInlineExpression() {
        return inlineExpression;
    }
}
